package io.cloud.tec.jdk.concurrent;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * https://blog.csdn.net/qq_45888932/article/details/124111106
 *
 */
public class AtomicThread extends Thread{

    private AtomicInteger currentCount;
    private String name;


    private static final Integer maxCount = 100;

    private static String[] chars = {"1", "2", "3"};

    public AtomicThread(String name, AtomicInteger currentCount) {
        this.name = name;
        this.currentCount = currentCount;
    }

    @Override
    public void run() {
        // println和getAndIncrement不是原子操作，可能发生getAndIncrement后，立即比较equals，其他线程会插入进来。所以会出现分隔线打印位置不正确
        while (currentCount.get() < maxCount) {
            if (this.name.equals(chars[currentCount.get() % 3])) {
                System.out.println(this.name);
                if (this.name.equals("3")) {
                    System.out.println("-------------------");
                }
                currentCount.getAndIncrement();
            }

        }
    }
}

class MainByAtomicThread {
    public static void main(String[] args) {

        AtomicInteger target = new AtomicInteger(0);
        new AtomicThread("1", target).start();
        new AtomicThread("2", target).start();
        new AtomicThread("3", target).start();
    }
}